<template>
  <div class="options-input">
    <ul class="options">
      <li v-for="item in formOptions" :key="item.id" class="options-item">
        <mu-text-field v-model="item.text" full-width :placeholder="`请在这里输入选项${item.tag}的内容`" class="input-low-padding"></mu-text-field>
      </li>
    </ul>
    <div class="options-action">
      <mu-button color="primary" @click="addOption()">添加一个空白选项</mu-button>
      <mu-button color="error" @click="popOption()">删除最后一个选项</mu-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'OptionsInput',
  props: {
    value: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      formOptions: []
    }
  },
  computed: {
    stringOptions() {
      return this.converOut(this.formOptions)
    },
    watchOptions() {
      return JSON.stringify(this.stringOptions)
    }
  },
  watch: {
    value(val) {
      this.formOptions = this.converIn(val)
    },
    watchOptions() {
      this.$emit('input', this.stringOptions)
    }
  },
  created() {
    this.formOptions = this.converIn(this.value)
  },
  methods: {
    // 将字符串数组转成选项数组
    converIn(strings) {
      const result = []
      for (let i = 0; i < strings.length; i++) {
        result.push({
          id: i + 1,
          tag: String.fromCharCode(65 + i),
          text: strings[i]
        })
      }
      return result
    },
    // 将选项数组转成字符串数组
    converOut(options) {
      return options.map(it => it.text)
    },
    // 添加一个空选项
    addOption() {
      const options = this.formOptions
      options.push({
        id: options.length + 1,
        tag: String.fromCharCode(65 + options.length),
        text: ''
      })
    },
    // 删除最后一个选项
    popOption() {
      if (this.formOptions.length > 0) {
        this.formOptions.pop()
      }
    }
  }
}
</script>

<style scoped>
.options {
  list-style: none;
}
.options-item {
  display: flex;
}
.options-action {
  display: flex;
  justify-content: space-between;
}
</style>
